import paramiko
import pymysql
import time
from ftplib import FTP
import datetime


ext_flag = False


def bop_update(ip,port,username,password,to_path,get_war,ftp_ip,ftp_port,ftp_path,ftp_user,ftp_password,war_path):
    ftp = FTP()
    ftp.set_debuglevel(2)
    ftp.connect(ftp_ip, ftp_port)
    ftp.login(ftp_user, ftp_password)
    ftp.cwd(ftp_path.encode("UTF-8").decode("latin-1"))
    ftp.cwd(war_path.encode("UTF-8").decode("latin-1"))
    size = []
    percent = []
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, password)
    path_list = str(to_path).split("/")
    if len(path_list) >= 3:
        tomcat_unique = path_list[-3]
        if len(tomcat_unique.strip()) == 0 or tomcat_unique is None:
            tomcat_unique = 'tomcat'
    else:
        tomcat_unique = 'tomcat'

    ssh_command = 'ps -ef|grep {} |grep -v grep | cut -c 9-15 | xargs kill -s 9 ;'.format(tomcat_unique)
    ssh.exec_command(ssh_command)
    for x in get_war:
        if x == 'bop-ext.war':
            global ext_flag
            ext_flag = True
        size.append(ftp.size(x))
        percent.append(0)
        a = x.split('.')[0]
        ssh.exec_command('cd {} ;rm -f {};'.format(to_path,x))
        time.sleep(1)
        ssh.exec_command('cd {} ;rm -rf {};'.format(to_path,a))
        time.sleep(1)

        #print('aaaaaaaa'+to_path,x,ftp_user,ftp_password,ftp_ip,ftp_port,ftp_path,war_path,x)
        ssh.exec_command('cd {} ; wget -b -q -O {} --ftp-user={} --ftp-password=\'{}\' ftp://{}:{}{}{}/{}'.format(to_path,x,ftp_user,ftp_password,ftp_ip,ftp_port,ftp_path,war_path,x))
        time.sleep(1)
        # zhukd28450 20200513添加 下载完后自动解压
        stdin, stdout, stderr = ssh.exec_command('unzip -oq {}/{} -d {}/{}'.format(to_path, x, to_path, a))
        print(stdout.read().decode())
        time.sleep(1)
    if ext_flag:
        # 对ext包的特殊处理
        ssh.exec_command('mv {}/bop-ext/bop-acct/WEB-INF/lib/*.jar {}/bop-acct/WEB-INF/lib/'.format(to_path, to_path))
        time.sleep(1)
        ext_flag = False

    for i in range(0,1000):
        for w in range(0,len(get_war)):
            stdin, stdout, stderr = ssh.exec_command('cd {} ; stat -c%s {}'.format(to_path, get_war[w]))
            now = stdout.read().decode()
            percent[w] = int(now)*100/int(size[w])
        print(max(percent))
        print(min(percent))
        if (int(max(percent)) == 100)&(int(min(percent)) == 100):
            time.sleep(1)
            bin_path = to_path.replace('webapps', 'bin')
            stdin, stdout, stderr = ssh.exec_command("source /etc/profile ;cd {} ; ./startup.sh".format(bin_path))
            print(stdout.read())
            ssh.close()
            break



if __name__ == '__main__':
    while True:
        try:
            conn = pymysql.connect(host='10.20.27.20', user='root', passwd='Dar960207!@#', db='dar')
            cur = conn.cursor()
            # 从bopupdateturn中获取待升级程序信息
            sql_1 = 'select bop_ip,bop_path,bop_war,id,up_persion,path_name,to_path_name from bopupdateturn where up_status = 1 order by id asc limit 1'
            num = cur.execute(sql_1)
            data = cur.fetchall()
            # 获取tomcat唯一标识字段


            if num == 1:
                bop_war = data[0][2].split(' ')  # bop-trade.war
                bop_ip =data[0][0]  # 10.20.37.21
                path_name = data[0][5]  # 21_trade取包路径
                to_path_name = data[0][6]  # 21_升级路径
                bop_path = data[0][1]  # SVN216636-2019-03-13_17-32-28
                turn_id = data[0][3]
                sql_2 = 'select path_ip,path_port,get_path,path_user,path_password from updatepath where path_name = "{}"'.format(path_name)
                #ftp取包路径信息
                num1 = cur.execute(sql_2)
                data1 = cur.fetchall()
                ftp_ip = data1[0][0]  # 192.168.102.180
                ftp_port = data1[0][1]  # 5212
                ftp_get_path = data1[0][2]  # /Webcodes/
                ftp_user = data1[0][3]
                ftp_password = data1[0][4]

                sql_3 = 'select path_port,path_user,path_password,to_path,path_ip from updatepath where path_name = "{}"'.format(to_path_name)
                #升级环境信息
                num2 = cur.execute(sql_3)
                data2 = cur.fetchall()
                ssh_ip = data2[0][4]  # 10.20.37.21
                ssh_port = data2[0][0] # 22
                ssh_user = data2[0][1]  # root
                ssh_password = data2[0][2]
                ssh_to_path = data2[0][3]

                bop_update(ssh_ip,ssh_port,ssh_user,ssh_password,ssh_to_path,bop_war,ftp_ip,ftp_port,ftp_get_path,ftp_user,ftp_password,bop_path)
                now_time = datetime.datetime.now().strftime('%H:%M:%S')
                sql_4 = 'update bopupdateturn set up_status = 2 where id = "{}"'.format(turn_id)
                sql_5 = 'insert into updatejour(output,read_status,update_time,message,up_persion)value("{0}",1,"{1}","{2}","{3}");'.format(bop_path, now_time, bop_war, data[0][4])
                num3 = cur.execute(sql_4)
                num4 = cur.execute(sql_5)
                conn.commit()

            else:
               # print('没有升级')
                pass
        except:
            sql_6 = 'update bopupdateturn set up_status = 2 where id = "{}"'.format(turn_id)
            num5 = cur.execute(sql_6)
            conn.commit()

        cur.close()
        conn.close()
        time.sleep(5)